package com.atguigu.service.impl;

import com.atguigu.bean.*;
import com.atguigu.dao.BookDao;
import com.atguigu.dao.OrderDao;
import com.atguigu.dao.OrderItemDao;
import com.atguigu.dao.impl.BookDaoImpl;
import com.atguigu.dao.impl.OrderDaoImpl;
import com.atguigu.dao.impl.OrderItemDaoImpl;
import com.atguigu.service.OrderService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Date:2020/9/16
 * Author:ybc
 * Description:
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();

    @Override
    public String checkOut(Cart cart, User user) {
        /**
         * 结账：
         *  1、保存订单
         *  2、保存订单项
         *  3、更新库存和销量
         */
        //将当前时间所对应的时间戳（即毫秒数）作为订单编号
        String orderId = System.currentTimeMillis() + "";
        //获取系统当前时间，即订单的创建时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = sdf.format(date);
        //将购物车对象转换为订单对象
        Order order = new Order(orderId, createTime, cart.getTotalCount(), cart.getTotalAmount(), 0, user.getId());
        //结账第一步：保存订单
        orderDao.saveOrder(order);
        //获取购物车中的所有购物项
        List<CartItem> cartItemList = cart.getCartItemList();
        //循环所有的购物项，将购物项转换为订单项
         for (CartItem cartItem : cartItemList) {
            //通过购物项对象获取订单项对象
            Book book = cartItem.getBook();
            OrderItem orderItem = new OrderItem(null, book.getTitle(), book.getAuthor(), book.getPrice(), book.getImgPath(), cartItem.getCount(), cartItem.getAmount(), orderId);
            //结账第二步：保存订单项
            orderItemDao.saveOrderItem(orderItem);
            //结账第三步：更新库存和销量
            bookDao.updateSalesAndStock(book.getId(), cartItem.getCount());
        }
        return orderId;
    }

    @Override
    public List<Order> getMyOrder(Integer userId) {
        return orderDao.getMyOrder(userId);
    }

    @Override
    public List<Order> getAllOrder() {
        return orderDao.getAllOrder();
    }

    @Override
    public List<OrderItem> getDetails(String orderId) {
        return orderItemDao.getDetails(orderId);
    }

    @Override
    public void sendOrder(String orderId) {
        orderDao.updateStatus(orderId, 1);
    }

    @Override
    public void takeOrder(String orderId) {
        orderDao.updateStatus(orderId, 2);
    }
}
